package com.szholly.pro.watergas_server.ps.android.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.UUID;

import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.utils.util.JSONUtils;
import com.szholly.data.common.util.JSONConvertUtils;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class SurfaceService {
	/**
	 * 获取地表水日常巡检项
	 */
	public String getDailyCheckItem() throws Exception {

		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String fatherSql = "select S_DOMAINCODE \"id\",S_DOMAINCAPTION \"name\" from data_defulatdomain where S_DOMAINNAME = '地表水运维项' and I_JB ='2' and S_DOMAINCODE like 'A01%' ORDER BY S_DOMAINCODE";
		String childSql = "select S_DOMAINCODE \"id\",S_DOMAINCAPTION \"name\" from data_defulatdomain where S_DOMAINNAME = '地表水运维项' and I_JB ='3'";
		// 1.先搜索地表水2级目录
		List<RowBase> fatherList = DataUtil.getSelectRows(fatherSql, parms);

		// 响应结果
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();

		if (fatherList != null && fatherList.size() > 0) {
			List<RowBase> childList;
			String sql;
			String id;
			String name;
			HashMap<String, Object> father;
			for (RowBase bean : fatherList) {
				try {
					id = bean.get("id").toString();
					name = bean.get("name").toString();
					sql = childSql + " and S_DOMAINCODE like '" + id + "%' ORDER BY S_DOMAINCODE";
					// 2.再搜索地表水3级目录
					childList = DataUtil.getSelectRows(sql, parms);
					father = new HashMap<String, Object>();
					father.put("id", id);
					father.put("name", name);
					father.put("childList", childList);
					resultList.add(father);
				} catch (Exception e) {
				}
			}
			JSONArray jsonArray = JSONArray.fromObject(resultList);
			return jsonArray.toString();
		} else {
			return new JSONArray().toString();
		}
	}

	/**
	 * 获取地表水日常巡检详情
	 */
	public String getDailyCheckdetail(String tableName, String taskCode) {
		if (tableName.isEmpty() || taskCode.isEmpty()) {
			return "";
		}
		tableName = tableName.toUpperCase();
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String fatherSql = "select S_DOMAINCODE \"id\",S_DOMAINCAPTION \"name\" from data_defulatdomain where S_DOMAINNAME = '地表水运维项' and I_JB ='2' and S_DOMAINCODE like 'A01%' ORDER BY S_DOMAINCODE";
		// 1.获得一级目录
		List<RowBase> fatherList = DataUtil.getSelectRows(fatherSql, parms);

		// 响应结果
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		if (null != fatherSql) {
			String id;
			String name;
			String childsql = "select t1.S_DOMAINCAPTION as name,t.GUID, t.item,t.ITEM_VALUE as value from " + tableName + " t left join   data_defulatdomain t1  " + " on t.item = t1.S_DOMAINCODE  where t1.S_DOMAINNAME = '地表水运维项' and t1.I_JB ='3' and t.task_code = '" + taskCode + "'";
			HashMap<String, Object> father;
			for (RowBase bean : fatherList) {
				String sql = null;
				id = bean.get("id").toString();
				name = bean.get("name").toString();
				sql = childsql + "and t.item like '" + id + "%' ORDER BY t.item desc";
				List<RowBase> childList = DataUtil.getSelectRows(sql, parms);
				father = new HashMap<String, Object>();
				father.put("id", id);
				father.put("name", name);
				father.put("childList", childList);
				resultList.add(father);
			}
			JSONArray jsonArray = JSONArray.fromObject(resultList);
			return jsonArray.toString();
		} else {
			return new JSONArray().toString();
		}
	}

	/**
	 * android地表水设备故障维修任务详情
	 * 
	 */

	public String getEquipmentRepairdetail(String tableName, String taskCode) {
		if (tableName.isEmpty() || taskCode.isEmpty()) {
			return "[]";
		}
		tableName = tableName.toUpperCase();
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select t1.c_userealname,t2.s_domaincaption,t.* from " + tableName + " t " + "left join safe_user t1 on t.repair_person = t1.s_userid " + "left join DATA_DEFULATDOMAIN t2 on t2.s_Domaincode = t.Failure_Reason " + "where t.task_id = '" + taskCode + "'and t2.S_DOMAINNAME ='地表水故障类型' ";
		// parms.add(new GlobalParameter("tableName", tableName));
		// parms.add(new GlobalParameter("taskCode", taskCode));
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "[]";
		}

	}

	/**
	 * android地表水标准物质更换任务详情
	 * 
	 */

	public String getSurfaceDetailStandardReplace(String tableName, String taskCode) {
		if (tableName.isEmpty() || taskCode.isEmpty()) {
			return "[]";
		}
		tableName = tableName.toUpperCase();
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select * from OPERATION_STANDARD_REPLACE t  where t.task_id = '" + taskCode + "'";
		// parms.add(new GlobalParameter("tableName", tableName));
		// parms.add(new GlobalParameter("taskCode", taskCode));
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "[]";
		}

	}

	/**
	 * android地表水标准物质更换任务详情
	 * 
	 */

	public String getSurfaceDetailReplacementReplace(String tableName, String taskCode) {
		if (tableName.isEmpty() || taskCode.isEmpty()) {
			return "[]";
		}
		tableName = tableName.toUpperCase();
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select * from OP_MATE_REPLACE t  where t.task_id = '" + taskCode + "'";
		// parms.add(new GlobalParameter("tableName", tableName));
		// parms.add(new GlobalParameter("taskCode", taskCode));
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "[]";
		}

	}

	/**
	 * 地表水1标样核查详情
	 * 
	 * @param tableName
	 * @param taskCode
	 * @param stationId
	 * @return
	 */
	public String getSurfaceStandardCheckDetail(String tableName, String taskCode, String stationId) {
		if (tableName.isEmpty() || taskCode.isEmpty() || stationId.isEmpty()) {
			return "[]";
		}
		tableName = tableName.toUpperCase();
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		String sql = "select t2.name,t3.s_domaincaption,t. * from OP_STAND_VERI t\n" + "   left join BC_SITE_POLL  t1 on t1.name = t.test_project\n" + "   left join BC_SITE_DEVICE_RPT  t2 on t2.monitor_point = t1.site_id and t2.guid = t1.device_id\n" + "   left join DATA_DEFULATDOMAIN t3 on t3.s_domaincode = t.test_project\n" + "   where t.task_code = '" + taskCode + "' and t1.site_id = '" + stationId + "'";

		// parms.add(new GlobalParameter("tableName", tableName));
		// parms.add(new GlobalParameter("taskCode", taskCode));
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);
		if (rows != null && rows.size() >= 0) {
			return JSONUtils.toJSONString(rows);
		} else {
			return "[]";
		}

	}

	/**
	 * 更新地表水日常校准
	 * 
	 */
	public String updateSurfaceDailyCalibration(String mapList) {
		JSONArray list = JSONUtils.toJSONArray(mapList);
		if (list.size() < 1) {
			return "{\"result\":false}";
		}
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
		int r = 0;
		for (int i = 0; i < list.size(); i++) {
			try {
				String GUID = list.getJSONObject(i).optString("GUID");
				if (null == GUID) {
					GUID = UUID.randomUUID().toString();
					String insertSql = "insert into OPERATION_DAILY_VERIFICATION (GUID,STATION_CODE,DEVICE_NUM,VERIFY_TYPE,VERIFY_DATE,VERIFY_RESULT,RESTORE_METHOD,CREATED_ON,CREATED_BY\n" + ",TASK_CODE,CALIBRATION_VALUE,CALIBRATION_LIQUID_ORDER,PARAMNAME)values(@GUID,@STATION_CODE,@DEVICE_NUM,@VERIFY_TYPE,@VERIFY_DATE,@VERIFY_RESULT,@RESTORE_METHOD,@CREATED_ON,@CREATED_BY\n" + ",@TASK_CODE,@CALIBRATION_VALUE,@CALIBRATION_LIQUID_ORDER,@PARAMNAME)";
					String STATION_CODE = list.getJSONObject(i).optString("STATION_CODE");
					String DEVICE_NUM = list.getJSONObject(i).optString("DEVICE_NUM");
					String VERIFY_TYPE = list.getJSONObject(i).optString("VERIFY_TYPE");
					String VERIFY_DATE = list.getJSONObject(i).optString("VERIFY_DATE");
					String VERIFY_RESULT = list.getJSONObject(i).optString("VERIFY_RESULT");

					String RESTORE_METHOD = list.getJSONObject(i).optString("RESTORE_METHOD");
					String CREATED_ON = list.getJSONObject(i).optString("CREATED_ON");
					String CREATED_BY = list.getJSONObject(i).optString("CREATED_BY");
					String TASK_CODE = list.getJSONObject(i).optString("TASK_CODE");
					String CALIBRATION_VALUE = list.getJSONObject(i).optString("CALIBRATION_VALUE");
					String CALIBRATION_LIQUID_ORDER = list.getJSONObject(i).optString("CALIBRATION_LIQUID_ORDER");
					String PARAMNAME = list.getJSONObject(i).optString("PARAMNAME");
					parms.add(new GlobalParameter("GUID", GUID));
					parms.add(new GlobalParameter("STATION_CODE", STATION_CODE));
					parms.add(new GlobalParameter("DEVICE_NUM", DEVICE_NUM));
					parms.add(new GlobalParameter("VERIFY_TYPE", VERIFY_TYPE));
					parms.add(new GlobalParameter("VERIFY_RESULT", VERIFY_RESULT));
					parms.add(new GlobalParameter("RESTORE_METHOD", RESTORE_METHOD));
					parms.add(new GlobalParameter("CREATED_BY", CREATED_BY));
					parms.add(new GlobalParameter("TASK_CODE", TASK_CODE));
					parms.add(new GlobalParameter("CALIBRATION_VALUE", CALIBRATION_VALUE));
					parms.add(new GlobalParameter("CALIBRATION_LIQUID_ORDER", CALIBRATION_LIQUID_ORDER));
					parms.add(new GlobalParameter("PARAMNAME", PARAMNAME));
					int g = DataUtil.ExecuteUpdateSql(insertSql, parms);
					if (g == 0) {
						continue;
					} else {
						return "{\"result\":false}";
					}
				}

				String sql = "update OPERATION_DAILY_VERIFICATION t set t.verify_type = @verify_type ," + "t.verify_result = @verify_result,t.CALIBRATION_VALUE = @CALIBRATION_VALUE," + "t.restore_method = @restore_method where t.GUID = @GUID";
				String verify_type = list.getJSONObject(i).optString("VERIFY_TYPE");
				String verify_result = list.getJSONObject(i).optString("VERIFY_RESULT");
				String CALIBRATION_VALUE = list.getJSONObject(i).optString("CALIBRATION_VALUE");
				String restore_method = list.getJSONObject(i).optString("RESTORE_METHOD");
				parms.add(new GlobalParameter("verify_type", verify_type));
				parms.add(new GlobalParameter("verify_result", verify_result));
				parms.add(new GlobalParameter("CALIBRATION_VALUE", CALIBRATION_VALUE));
				parms.add(new GlobalParameter("restore_method", restore_method));
				parms.add(new GlobalParameter("GUID", GUID));
				r = r + DataUtil.ExecuteUpdateSql(sql, parms);
			} catch (Exception e) {
				return "{\"result\":false}";
			}
		}
		if (r == 0) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}

	}

	/**
	 * 地表水标样核查详情更新
	 */
	public String updateStandardCheckDate(String listMap) {
		JSONArray itemList = JSONUtils.toJSONArray(listMap);
		if (itemList.size() < 1) {
			return "{\"result\":false}";
		}

		int r = 0;

		for (int j = 0; j < itemList.size(); j++) {
			List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
			JSONObject item = itemList.getJSONObject(j);
			String sql = "update OP_STAND_VERI t set t.config_value = @config_value,t.auto_result = @auto_result," + "t.auto_result1 = @auto_result1,t.auto_result2 = @auto_result2," + "t.zero_calibration_liquid = @zero_calibration_liquid,t.scale_calibration_liquid = @scale_calibration_liquid,\n" + " t.opposite_error = @opposite_error where t.GUID = @GUID";
			try {
				String GUID = item.optString("GUID");
				String configValue = item.optString("CONFIG_VALUE");
				String autoResult = item.optString("AUTO_RESULT");
				String autoResult1 = item.optString("AUTO_RESULT1");
				String autoResult2 = item.optString("AUTO_RESULT2");
				String zeroCalibrationLiquid = item.optString("ZERO_CALIBRATION_LIQUID");
				String scaleCalibrationLiquid = item.optString("SCALE_CALIBRATION_LIQUID");
				String oppositeError = item.optString("OPPOSITE_ERROR");
				parms.add(new GlobalParameter("GUID", GUID));
				parms.add(new GlobalParameter("config_value", configValue));
				parms.add(new GlobalParameter("auto_result", autoResult));
				parms.add(new GlobalParameter("auto_result1", autoResult1));
				parms.add(new GlobalParameter("auto_result2", autoResult2));
				parms.add(new GlobalParameter("zero_calibration_liquid", zeroCalibrationLiquid));
				parms.add(new GlobalParameter("scale_calibration_liquid", scaleCalibrationLiquid));
				parms.add(new GlobalParameter("opposite_error", oppositeError));
				r = r + DataUtil.ExecuteUpdateSql(sql, parms);
			} catch (Exception e) {

			}

		}
		if (r == 0) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}

	}

	/**
	 * 地表水水样比对详情更新
	 */
	public String updateWaterContrastData(String listMap) {
		JSONArray list = JSONArray.fromObject(listMap);
		if (list.size() < 1) {
			return "{\"result\":false}";
		}
		int r = 0;
		for (int j = 0; j < list.size(); j++) {
			List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
			JSONObject item = list.getJSONObject(j);
			String sql = "update OP_SAMPLE_COMP t set t.manual_measure_one = @manual_measure_one," + "t.manual_measure_two = @manual_measure_two,t.manual_average = @manual_average,\n" + "t.real_measure_one = @real_measure_one,t.real_measure_two = @real_measure_two," + "t.real_measure_avg = @real_measure_avg,MEASURE_DEVIATION = @MEASURE_DEVIATION where t.guid = @guid";

			try {
				String GUID = item.optString("GUID");
				String manual_measure_one = item.optString("MANUAL_MEASURE_ONE");
				String manual_measure_two = item.optString("MANUAL_MEASURE_TWO");
				String manual_average = item.optString("MANUAL_AVERAGE");
				String real_measure_one = item.optString("REAL_MEASURE_ONE");
				String real_measure_two = item.optString("REAL_MEASURE_TWO");
				String real_measure_avg = item.optString("REAL_MEASURE_AVG");
				String MEASURE_DEVIATION = item.optString("MEASURE_DEVIATION");
				parms.add(new GlobalParameter("guid", GUID));
				parms.add(new GlobalParameter("manual_measure_one", manual_measure_one));
				parms.add(new GlobalParameter("manual_measure_two", manual_measure_two));
				parms.add(new GlobalParameter("manual_average", manual_average));
				parms.add(new GlobalParameter("real_measure_one", real_measure_one));
				parms.add(new GlobalParameter("real_measure_two", real_measure_two));
				parms.add(new GlobalParameter("real_measure_avg", real_measure_avg));
				parms.add(new GlobalParameter("MEASURE_DEVIATION", MEASURE_DEVIATION));
				r = r + DataUtil.ExecuteUpdateSql(sql, parms);
			} catch (Exception e) {

			}
		}
		if (r == 0) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}

	}

	/**
	 * 地表水标准物质更换详情更新
	 */
	public String updateStandardReplace(String listMap) {
		JSONArray list = JSONArray.fromObject(listMap);
		if (list.size() < 1) {
			return "{\"result\":false}";
		}
		int r = 0;
		for (int j = 0; j < list.size(); j++) {
			List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
			JSONObject item = list.getJSONObject(j);
			String sql = "update OPERATION_STANDARD_REPLACE t set t.sub_name = @sub_name, t.make_time = @make_time, t.replace_time = @replace_time,t.useful_time = @useful_time where t.guid = @guid";

			try {
				String GUID = item.optString("GUID");
				String sub_name = item.optString("SUB_NAME");
				String make_time = item.optString("MAKE_TIME");
				String replace_time = item.optString("REPLACE_TIME");
				String useful_time = item.optString("USEFUL_TIME");
				Date makeTime = null;
				Date replaceTime = null;
				try {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					makeTime = sdf.parse(make_time);
					replaceTime = sdf.parse(replace_time);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				parms.add(new GlobalParameter("guid", GUID));
				parms.add(new GlobalParameter("sub_name", sub_name));
				if (null != makeTime) {
					parms.add(new GlobalParameter("make_time", makeTime));
				}
				if (null != replaceTime) {
					parms.add(new GlobalParameter("replace_time", replaceTime));
				}

				parms.add(new GlobalParameter("useful_time", useful_time));
				r = r + DataUtil.ExecuteUpdateSql(sql, parms);
			} catch (Exception e) {

			}
		}
		if (r == 0) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}

	}

	/**
	 * 地表水备件耗材更换详情更新
	 */
	public String updateReplacementReplace(String listMap) {
		JSONArray list = JSONArray.fromObject(listMap);
		if (list.size() < 1) {
			return "{\"result\":false}";
		}
		int r = 0;
		for (int j = 0; j < list.size(); j++) {
			List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
			JSONObject item = list.getJSONObject(j);
			String sql = "update OP_MATE_REPLACE t set t.material_quantity = @material_quantity where t.guid = @guid";

			try {
				String GUID = item.optString("GUID");
				String number = item.optString("MATERIAL_QUANTITY");
				float upNumber = 0;
				try {
					if (null != number) {
						upNumber = Float.parseFloat(number);
					}
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				parms.add(new GlobalParameter("guid", GUID));
				parms.add(new GlobalParameter("material_quantity", upNumber));
				r = r + DataUtil.ExecuteUpdateSql(sql, parms);
			} catch (Exception e) {

			}
		}
		if (r == 0) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}

	}

	/**
	 * 地表水备件耗材更换详情更新
	 */
	public String updateEquipmentRepair(String listMap) {
		JSONArray list = JSONArray.fromObject(listMap);
		if (list.size() < 1) {
			return "{\"result\":false}";
		}
		int r = 0;
		for (int j = 0; j < list.size(); j++) {
			List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
			JSONObject item = list.getJSONObject(j);
			String sql = "update OP_FAILURE_REPAIR t set t.repair_method = @repair_method ,t.failure_reason_note = @failure_reason_note,t.repair_result = @repair_result where t.guid = @guid";

			try {
				String GUID = item.optString("GUID");
				String repair_method = item.optString("REPAIR_METHOD");
				String failure_reason_note = item.optString("FAILURE_REASON_NOTE");
				String repair_result = item.optString("REPAIR_RESULT");
				parms.add(new GlobalParameter("guid", GUID));
				parms.add(new GlobalParameter("repair_method", repair_method));
				parms.add(new GlobalParameter("failure_reason_note", failure_reason_note));
				parms.add(new GlobalParameter("repair_result", repair_result));
				r = r + DataUtil.ExecuteUpdateSql(sql, parms);
			} catch (Exception e) {

			}
		}
		if (r == 0) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}

	}

	/**
	 * 地表水日常巡检更新
	 */
	public String updateDetailDailyCheck(String GUID,String STATUS) {

		int r = 0;
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();

		String sql = "update OP_RECO_RPT t set t.ITEM_VALUE = @ITEM_VALUE where t.GUID = @GUID";
		try {
		
			parms.add(new GlobalParameter("GUID", GUID));
			parms.add(new GlobalParameter("ITEM_VALUE", Integer.parseInt(STATUS)));

			r = DataUtil.ExecuteUpdateSql(sql, parms);
		} catch (Exception e) {

		}
		if (r == 0) {
			return "{\"result\":true}";
		} else {
			return "{\"result\":false}";
		}
	}

	/**
	 * android签到时间
	 * 
	 * @param userName
	 * @param password
	 * @return
	 * @throws Exception
	 */

	public String getSignIn(String userName, String scId) {
		List<GlobalParameter> parms = new ArrayList<GlobalParameter>();

		String sql = "select to_char(CT,'yyyy-mm-dd') as ct from (select  * from OP_REGI_INFO  where USER_ID = '" + userName + "' and WTTP_ID = '" + scId + "'and CT is not null order by CT desc) where rownum=1";
		List<RowBase> rows = DataUtil.getSelectRows(sql, parms);

		if (rows != null && rows.size() > 0) {
			String result = JSONUtils.toJSONString(rows);
			return result;
		} else {
			return "[]";
		}
	}

	/**
	 * 方法名称:transStringToMap 传入参数:mapString 形如 username'chenziwen^password'1234
	 * 返回值:Map
	 */
	public Map transStringToMap(String mapString) {
		Map map = new HashMap();
		StringTokenizer items;
		for (StringTokenizer entrys = new StringTokenizer(mapString, "^"); entrys.hasMoreTokens(); map.put(items.nextToken(),
				items.hasMoreTokens() ? ((Object) (items.nextToken())) : null))
			items = new StringTokenizer(entrys.nextToken(), "'");
		return map;
	}

}
